//
//  MainTableViewController.m
//  ZhiHuDaily
//
//  Created by albert on 16/8/14.
//  Copyright © 2016年 albert. All rights reserved.
//  这其实是个UIViewController

#import "MainTableViewController.h"
#import <MJRefresh/MJRefresh.h>
#import "NetworkingTool.h"
#import "NewsListModel.h"
#import "NewsListCell.h"
#import "NewsDetailViewController.h"
#import "MainHeaderView.h"
#import "NavBarView.h"
#import "MainSectionHeaderView.h"
#import "JKDateTool.h"
#import "RefreshProgressView.h"
#import "SQLiteManager.h"
#import "NewsListGetDataModel.h"
#import "MainNavigationController.h"
#import "HomeTableView.h"

@interface MainTableViewController () <UITableViewDataSource, UITableViewDelegate, UIViewControllerPreviewingDelegate, MainHeaderViewDelegate>

/** 模型数组 */
@property (nonatomic, strong) NSMutableArray *stories;

/** 日期数组 */
@property (nonatomic, strong) NSMutableArray *loadedDate;

/** 格式化的日期数组 */
@property (nonatomic, strong) NSMutableArray *fmtDateArr;

/** 顶部图片轮播view */
@property (nonatomic, weak) MainHeaderView *mainHeaderView;

/** tableView */
@property (nonatomic, weak) HomeTableView *tableView;

/** 自定义导航栏 */
@property (nonatomic, weak) NavBarView *navBarView;

/** 状态栏 */
@property (nonatomic, weak) UIView *statusBarView;

/** 自定义导航栏背景透明度 */
@property (nonatomic, assign) CGFloat bgAlpha;

/** 刷新控件 */
@property (nonatomic, weak) RefreshProgressView *refreshView;

/** 当前皮肤模式 */
@property (nonatomic, copy) NSString *currentSkinModel;

/** 重新加载按钮 */
@property (nonatomic, weak) UIButton *reloadBtn;

/** 阅读提醒label */
@property (nonatomic, weak) UILabel *readNoticeLabel;

/** 第一次启动时遮盖的view */
@property (nonatomic, weak) UIView *coverView;
@end

@implementation MainTableViewController

#pragma mark - 常量
/** cell重用ID */
static NSString * const newsListID = @"newsList";

/** cell高度 80 */
static CGFloat const tableViewRowH = 80;

/** 动画时间 */
static CGFloat const animaitionDuration = 0.25;

#pragma mark - 懒加载
- (UIButton *)reloadBtn{
    
    if (!_reloadBtn) {
        
        UIButton *reloadBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        reloadBtn.titleLabel.numberOfLines = 0;
        reloadBtn.titleLabel.font = [UIFont systemFontOfSize:12];
        reloadBtn.hidden = YES;
        [reloadBtn setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
        [reloadBtn setTitle:@"加载数据失败，点击重新加载" forState:(UIControlStateNormal)];
        [reloadBtn addTarget:self action:@selector(loadNewLists) forControlEvents:(UIControlEventTouchUpInside)];
        [self.view addSubview:reloadBtn];
        _reloadBtn = reloadBtn;
    }
    return _reloadBtn;
}

- (UIView *)coverView{
    
    if (!_coverView) {
        
        UIView *coverView = [[UIView alloc] init];
        coverView.backgroundColor = [UIColor blackColor];
        coverView.hidden = YES;
        coverView.alpha = 0.9;
        coverView.frame = [UIScreen mainScreen].bounds;
        [self.view addSubview:coverView];
        _coverView = coverView;
    }
    return _coverView;
}

- (UILabel *)readNoticeLabel{
    
    if (!_readNoticeLabel) {
        
        UILabel *label = [[UILabel alloc] init];
        label.backgroundColor = JKMainColor;
        label.text = @"       上次看到这里了哦~";
        label.font = [UIFont systemFontOfSize:12];
        label.frame = CGRectMake(-138, 0, 138, 25);
        label.hidden = YES;
        label.textColor = [UIColor whiteColor];
        label.layer.cornerRadius = label.height * 0.5;
        label.layer.masksToBounds = YES;
        label.textAlignment = NSTextAlignmentLeft;
        [self.view addSubview:label];
        _readNoticeLabel = label;
    }
    return _readNoticeLabel;
}

- (RefreshProgressView *)refreshView{
    
    if (!_refreshView) {
        
        RefreshProgressView *refreshView = [[RefreshProgressView alloc] init];
        refreshView.backgroundColor = [UIColor clearColor];
        refreshView.frame = CGRectMake(JKScreenW * 0.5 - 30 - 38, 33, 24, 24);
        refreshView.centerY = self.navBarView.defaltCenter.y;
        [self.view addSubview:refreshView];
        _refreshView = refreshView;
    }
    return _refreshView;
}

- (MainHeaderView *)mainHeaderView{
    
    if (!_mainHeaderView) {
        
        MainHeaderView *mainHeaderView = [[MainHeaderView alloc] initWithFrame:CGRectMake(0, -80, JKScreenW, JKScreenW * 0.85)];
        
        mainHeaderView.delegate = self;
        
        [self.tableView insertSubview:mainHeaderView atIndex:0];
        self.tableView.mainHeaderView = mainHeaderView;
        
        _mainHeaderView = mainHeaderView;
    }
    return _mainHeaderView;
}

- (HomeTableView *)tableView{
    
    if (!_tableView) {
        
        HomeTableView *tableView = [[HomeTableView alloc] initWithFrame:(CGRectMake(0, 0, JKScreenW, JKScreenH)) style:(UITableViewStylePlain)];
        
        [tableView jk_adapt_iOS_11_scrollView];
        tableView.backgroundColor = nil;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.rowHeight = tableViewRowH;
        
        // 注册cell
        [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([NewsListCell class]) bundle:nil] forCellReuseIdentifier:newsListID];
        
        [self.view addSubview:tableView];
        tableView.tableFooterView = [[UIView alloc] init];
        
        _tableView = tableView;
    }
    return _tableView;
}

- (UIView *)statusBarView{
    
    if (!_statusBarView) {
        
        UIView *statusBarView = [[UIView alloc] init];
        statusBarView.hidden = YES;
        statusBarView.frame = CGRectMake(0, 0, JKScreenW, JKStatusBarHeight);
        statusBarView.backgroundColor = JKMainColor;
        [self.view addSubview:statusBarView];
        
        _statusBarView = statusBarView;
    }
    return _statusBarView;
}

- (NSMutableArray *)loadedDate{
    
    if (!_loadedDate) {
        
        _loadedDate = [NSMutableArray array];
    }
    return _loadedDate;
}

- (NSMutableArray *)fmtDateArr{
    
    if (!_fmtDateArr) {
        
        _fmtDateArr = [NSMutableArray array];
    }
    return _fmtDateArr;
}

- (NSMutableArray *)stories{
    
    if (!_stories) {
        
        _stories = [NSMutableArray array];
    }
    return _stories;
}

#pragma mark - 生命周期方法
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        self.coverView.hidden = NO;
        
        [UIView animateWithDuration:animaitionDuration * 3 animations:^{
            
            self.coverView.backgroundColor = JKGlobalBgColor;
            self.coverView.alpha = 0;
            
        } completion:^(BOOL finished) {
            
            [self.coverView removeFromSuperview];
        }];
    });
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSkin) name:JKSkinModelDidChangedNotification object:nil];
    [self updateSkin];
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:JKReadPositionNoticeOffKey]) return;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(lastReadNotice:) name:JKLastReadIndexNotification object:nil];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    [self mainHeaderViewAddTimer];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [self mainHeaderViewRemoveTimer];
}

- (void)lastReadNotice:(NSNotification *)noti{
    
    NSIndexPath *indexPath = noti.userInfo[JKLastReadIndexKey];
    
    [UIView animateWithDuration:0.5 animations:^{
       
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:(UITableViewScrollPositionNone) animated:NO];
    }];
    
    NewsListCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    
    CGRect rect = [self.tableView convertRect:cell.frame toView:self.view];
    
    self.readNoticeLabel.y = rect.origin.y + (rect.size.height - self.readNoticeLabel.height) * 0.5;
    self.readNoticeLabel.hidden = NO;
    
    [UIView animateWithDuration:animaitionDuration delay:0.5 options:0 animations:^{
        
        self.readNoticeLabel.x = -self.readNoticeLabel.height * 0.5;
        
    } completion:^(BOOL finished) {
        
        [UIView animateWithDuration:animaitionDuration delay:animaitionDuration * 5 options:0 animations:^{
            
            self.readNoticeLabel.x = -self.readNoticeLabel.width;
            
        } completion:^(BOOL finished) {
            
            self.readNoticeLabel.hidden = YES;
        }];
    }];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 刷新为已读颜色
- (void)reloadReadStoryWithIndexPath:(NSIndexPath *)indexPath{
    
    if ([self.stories.firstObject count] <= 0) {
        return;
    }
    
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationNone)];
}

/** 针对3DTouch跳转返回后 刷新已读字体颜色 */
- (void)reload3DTouchReadWithID:(int)storyID{
    
    if ([self.stories.firstObject count] <= 0) {
        return;
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        NSInteger count = [self.stories.firstObject count];
        
        for (NSInteger i = 0; i < count; i++) {
            
            NewsListModel *md = [self.stories.firstObject objectAtIndex:i];
            
            if (md.ID != storyID) continue;
            
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            
            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationNone)];
            
            break;
        }
    });
}

#pragma mark - 初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"JKInstalledKey"]) {
        
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"JKInstalledKey"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"说明" message:@"\n本人iOSer一枚，常看知乎日报，奈何官方APP到现在还没有适配iPhone X，故优化更新此项目。\n\n此项目为本人早前学习开发用来练手的项目，接口信息为网络上他人分享获取，故无法真正登录也无法发表评论。分享功能仅支持微信、微博、短信及链接复制。\n\n本人能力有限，可能做的不够完美，如有各种bug出现，欢迎在【设置】中获取联系方式与我联系~" preferredStyle:(UIAlertControllerStyleAlert)];
        
        [alertVc addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        
        [self presentViewController:alertVc animated:YES completion:nil];
    }
    
    self.tableView.showsVerticalScrollIndicator = NO;
    
    self.tableView.contentInset = UIEdgeInsetsMake(JKStatusBarHeight, 0, 0, 0);
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    UIView *tableHeader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.width, JKScreenW * 0.85 - 120 - 20)];
    tableHeader.userInteractionEnabled = NO;
    self.tableView.tableHeaderView = tableHeader;
    
    [self mainHeaderView];
    
    // 设置刷新控件
    [self setupRefresh];
    
    // 初始化导航栏
    [self setupNavBar];
    
    [self loadNewLists];
    
    if ([UIDevice currentDevice].systemVersion.doubleValue >= 9.0) {
        // 注册3DTouch
        if (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable) {
            [self registerForPreviewingWithDelegate:self sourceView:self.tableView];
        }
    }
}

// 初始化导航栏
- (void)setupNavBar{
    
    NavBarView *navBarView = [NavBarView barViewWithTitle:@"今日热闻" showBackTitle:NO];
    navBarView.bgAlpha = 0;
    [self.view addSubview:navBarView];
    self.navBarView = navBarView;
    
    UIImageView *imgView = [[UIImageView alloc] init];
    imgView.image = [UIImage imageNamed:@"Home_Icon"];
    imgView.frame =  CGRectMake(10, 33, 18, 18);
    [self.navBarView insertSubview:imgView atIndex:0];
    imgView.centerY = navBarView.defaltCenter.y;
    
    UIButton *leftBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    leftBtn.backgroundColor = [UIColor clearColor];
    leftBtn.frame = CGRectMake(0, 30, 50, 28);
    [leftBtn addTarget:self action:@selector(leftBtnClick:) forControlEvents:(UIControlEventTouchUpInside)];
    self.navBarView.leftButton = leftBtn;
    leftBtn.centerY = navBarView.defaltCenter.y;
}

// 设置刷新控件
- (void)setupRefresh{
    
    self.tableView.mj_header = [MJRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewLists)];
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreLists)];
    self.tableView.mj_footer.hidden = YES;
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    
    self.reloadBtn.frame = CGRectMake(20, (JKScreenH - 60) * 0.5, self.view.width - 40, 60);
}

// 获取最新数据
- (void)loadNewLists{
    
    [[NetworkingTool sharedNetworkingTool].operationQueue cancelAllOperations];
    [self.tableView.mj_footer endRefreshing];
    [self.refreshView beginAnimating];
    
    [NewsListGetDataModel loadLatestDatafWithFinishedBlock:^(NSDictionary *dict, NSError *error) {
        
        [self.tableView.mj_header endRefreshing];
        [self.refreshView stopAnimating];
        
        if (error || dict == nil) {
            
            if (self.stories.count > 0 && [self.stories.firstObject count] > 0) {
                return;
            }
            
            self.tableView.hidden = YES;
            self.reloadBtn.hidden = NO;
            return;
        }
        
        self.tableView.hidden = NO;
        [self.reloadBtn removeFromSuperview];
        self.tableView.mj_footer.hidden = NO;
        
        // 设置顶部轮播图数据
        NSArray *top_stories = dict[JKTopStoryListKey];
        self.mainHeaderView.storyIDs = [top_stories valueForKeyPath:@"id"];
        [self.mainHeaderView setImageUrls:[top_stories valueForKeyPath:@"image"] titles:[top_stories valueForKeyPath:@"title"]];
        
        NSMutableArray *todayStories = [NSMutableArray arrayWithArray:dict[JKStoryListKey]];
        NSString *todayDateStr = dict[JKStoryDateKey];
        
        if (self.stories.count > 0 &&
            [self.stories.firstObject count] > 0 &&
            self.loadedDate.count > 0) {
            
            if ([self.stories.firstObject count] == todayStories.count &&
                [self.loadedDate.firstObject isEqualToString:todayDateStr]) {
                
                return;
            }
        }
        
        [self.stories removeAllObjects];
        [self.loadedDate removeAllObjects];
        [self.fmtDateArr removeAllObjects];
        
        [self.stories addObject:todayStories];
        
        // 自动离线还是放在这里吧
        if ([[NSUserDefaults standardUserDefaults] boolForKey:JKAutoDownloadKey]) {
            
            NSArray *arr = [dict[JKStoryListKey] valueForKeyPath:@"ID"];
            [SQLiteManager cacheDetailWithIDs:arr];
        }

        [self.loadedDate addObject:dict[JKStoryDateKey]];
        [self.fmtDateArr addObject:[self getFormatDate:dict[JKStoryDateKey]]];
        
        [self.tableView reloadData];
        [self loadMoreLists];
    }];
}

- (NSString *)getFormatDate:(NSString *)dateStr{
    
    NSString *monthStr = nil;
    NSString *dayStr = nil;
    if (dateStr.length >= 7) {// 安全校验一下
        monthStr = [dateStr substringWithRange:(NSMakeRange(4, 2))];
        dayStr = [dateStr substringFromIndex:6];
    }
    NSString *weekday = [JKDateTool getWeekdayOfSpecifiedDate:[dateStr intValue]];
    
    NSString *fmtDate = [NSString stringWithFormat:@"%@月%@日 %@", monthStr, dayStr, weekday];
    
    return fmtDate;
}

// 加载更多数据
- (void)loadMoreLists{
    
    [[NetworkingTool sharedNetworkingTool].operationQueue cancelAllOperations];
    [self.tableView.mj_footer endRefreshing];
    
    [NewsListGetDataModel loadMoreDataWithDate:[self.loadedDate.lastObject intValue] finishedBlock:^(NSDictionary *dict, NSError *error) {
        
        [self.stories addObject:dict[JKStoryListKey]];
        [self.loadedDate addObject:dict[JKStoryDateKey]];
        [self.fmtDateArr addObject:[self getFormatDate:dict[JKStoryDateKey]]];
        
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
    }];
}

#pragma mark - 按钮事件
// 左侧按钮点击
- (void)leftBtnClick:(UIButton *)button{
    
    MainNavigationController *mainNav = (MainNavigationController *)self.navigationController;
    !mainNav.showLeftVcBlock ? : mainNav.showLeftVcBlock();
    /** 不用代理了
    if ([self.delegate respondsToSelector:@selector(mainTableViewController:didClickLeftBtn:)]) {
        [self.delegate mainTableViewController:self didClickLeftBtn:button];
    } */
}

#pragma mark - UIViewControllerPreviewingDelegate
- (nullable UIViewController *)previewingContext:(id <UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location{
    
    self.readNoticeLabel.hidden = YES;
    
    // 1、获取sourceView
    UIView *sourceView = [previewingContext sourceView];
    
    /**通过坐标点获取 indexPath */
    /*
     同样如果sourceView != self.tableView的话，也需要转换坐标系
     */
    CGPoint point = [self.tableView convertPoint:location fromView:sourceView];
    
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:point];
    
    // 如果indexPath为nil，则直接返回nil
    if (!indexPath) return nil;
    
    /**获得当前cell */
    NewsListCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    // 设置sourceRect
    CGRect sourceRect = cell.frame;
    
    /*
     这里同时也涉及到坐标系转换
     sourceRect = [self.tableView convertRect:cell.frame toView:sourceView];
     */
    [previewingContext setSourceRect:sourceRect];
    
    NewsListModel *model = self.stories[indexPath.section][indexPath.row];
    
    NewsDetailViewController *detailViewController = [[NewsDetailViewController alloc] init];
    
    detailViewController.storyID = model.ID;
    detailViewController.stories = self.stories;
    detailViewController.indexPath = indexPath;
    detailViewController.storyListVc = self;
    
    return detailViewController;
}

- (void)previewingContext:(id <UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit{
    
    [self.navigationController pushViewController:viewControllerToCommit animated:YES];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.stories.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [self.stories[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NewsListCell *cell = [tableView dequeueReusableCellWithIdentifier:newsListID];
    NewsListModel *model = self.stories[indexPath.section][indexPath.row];
    
    model.alreadyRead = [SQLiteManager queryIsReadWithStoryID:model.ID];
    
    cell.model = model;

    // 切换皮肤
    if ([self.currentSkinModel isEqualToString:JKNightSkinModelValue]) {
        [cell changeToNightSkin];
        
    }else{
        [cell changeToDaySkin];
    }
    
    return cell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    self.readNoticeLabel.hidden = YES;
    NewsListModel *model = self.stories[indexPath.section][indexPath.row];
    
    NewsDetailViewController *detailViewController = [[NewsDetailViewController alloc] init];
    
    detailViewController.storyID = model.ID;
    detailViewController.stories = self.stories;
    detailViewController.indexPath = indexPath;
    detailViewController.storyListVc = self;
    
    [self.navigationController pushViewController:detailViewController animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return (section == 0) ? 0 : JKSectionHeaderH;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (section == 0) return nil;
    
    MainSectionHeaderView *sectionHeaderView = [MainSectionHeaderView headerViewWithTableView:tableView];
    sectionHeaderView.frame = CGRectMake(0, 0, JKScreenW, JKSectionHeaderH);
    
    sectionHeaderView.headerTitle = self.fmtDateArr[section];
    
    // 切换皮肤
    if ([self.currentSkinModel isEqualToString:JKNightSkinModelValue]) {
        [sectionHeaderView changeToNightSkin];
    }else{
        [sectionHeaderView changeToDaySkin];
    }
    
    return sectionHeaderView;
}

#pragma mark - scrollView delegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    self.readNoticeLabel.hidden = YES;
    [self mainHeaderViewRemoveTimer];
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    
    [self mainHeaderViewAddTimer];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    [self mainHeaderViewAddTimer];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    
    [self mainHeaderViewAddTimer];
}

- (void)mainHeaderViewAddTimer{
    
    if (self.tableView.contentOffset.y + 20 >= JKScreenW * 0.85 - 120 - 20) return;
    [self.mainHeaderView addTimer];
}

- (void)mainHeaderViewRemoveTimer{
    
    [self.mainHeaderView removeTimer];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (scrollView.contentOffset.y <= -scrollView.contentInset.top) {
        
        self.tableView.contentOffset = CGPointMake(0, (self.tableView.contentOffset.y <= -140) ? -140 : self.tableView.contentOffset.y);
    }
    
    // 刷新控件的进度
    self.refreshView.progress = ((self.tableView.contentOffset.y < -self.tableView.contentInset.top && self.tableView.mj_header.state != MJRefreshStateRefreshing)) ? -(self.tableView.contentOffset.y + self.self.tableView.contentInset.top) / 54.0 : 0;
    
    self.statusBarView.hidden = (scrollView.contentOffset.y < JKScreenW * 0.85 - 140);
    
    self.navBarView.bgAlpha = ((scrollView.contentOffset.y + 20) / (JKScreenW * 0.85 - 120));
    
    if (scrollView.contentOffset.y + scrollView.contentInset.top > (([self.stories.firstObject count]) * tableViewRowH + (JKScreenW * 0.85 - 140))) {
        
        self.navBarView.bgAlpha = 0;
    }
    
    self.navBarView.title = (scrollView.contentOffset.y + JKStatusBarHeight > ([self.stories.firstObject count]) * tableViewRowH + (JKScreenW * 0.85 - 140)) ? @"" : @"今日热闻";
//    NSLog(@"%.2f---%.2f---%.2f", self.navBarView.bgAlpha, scrollView.contentOffset.y + scrollView.contentInset.top, (([self.stories.firstObject count] - 1) * tableViewRowH + (JKScreenW * 0.85 - 140)));
    if (scrollView.contentOffset.y > JKScreenH) {
        return;
    }
    
    // 顶部图片轮播控件的Y值
    self.mainHeaderView.y = -80 - (-scrollView.contentOffset.y - 20) * 0.5;
    
    // 顶部图片轮播控件中的标题和pageControl的Y值
    [self.mainHeaderView setTitleLabelY:self.mainHeaderView.bounds.size.height-60-125 + (JKIsIphoneX ? 10 : 0) + (-scrollView.contentOffset.y - JKStatusBarHeight) * 0.5];
    [self.mainHeaderView setPageControlY:self.mainHeaderView.bounds.size.height - 92 + (JKIsIphoneX ? 10 : 0) + (-scrollView.contentOffset.y - JKStatusBarHeight) * 0.5];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    [self mainHeaderViewAddTimer];
}

#pragma mark - MainHeaderViewDelegate
- (void)mainHeaderView:(MainHeaderView *)mainHeaderView didClickCurrentImageViewWithID:(int)ID{
    
    NewsDetailViewController *detailViewController = [[NewsDetailViewController alloc] init];
    
    detailViewController.storyID = ID;
    detailViewController.stories = self.stories;
    detailViewController.isTop = YES;
    detailViewController.storyListVc = self;
    
    NSIndexPath *indexPath = nil;
    
    for (int i = 0; i < self.stories.count; i++) {
        NSArray *arr = self.stories[i];
        
        for (int j = 0; j < arr.count; j++) {
            NewsListModel *model = arr[j];
            if (model.ID == ID) {
                indexPath = [NSIndexPath indexPathForRow:j inSection:i];
                break;
            }
        }
    }
    
    detailViewController.indexPath = indexPath;
    
    [self.navigationController pushViewController:detailViewController animated:YES];
}

- (void)dealloc{
    JKLog(@"%d, %s",__LINE__, __func__);
}

#pragma mark - 更新皮肤
- (void)updateSkin{
    
    NSString *currentSkinModel = [[NSUserDefaults standardUserDefaults] objectForKey:JKCurrentSkinModelKey];
    
    if ([self.currentSkinModel isEqualToString:currentSkinModel]) {
        return;
    }
    
    [self.mainHeaderView updateSkin];
    
    self.currentSkinModel = currentSkinModel;
    
    if ([currentSkinModel isEqualToString:JKNightSkinModelValue]) { // 夜间模式
        self.view.backgroundColor = [UIColor blackColor];
        self.statusBarView.backgroundColor = JKColor(60, 60, 60);
        [self.navBarView changeToNightSkinWithBgAlpha:self.navBarView.bgAlpha];
        
    }else{ // 日间模式
        self.view.backgroundColor = JKGlobalBgColor;
        self.statusBarView.backgroundColor = JKMainColor;
        [self.navBarView changeToDaySkinWithBgAlpha:self.navBarView.bgAlpha];
    }
    
    [self.tableView reloadData];
}
@end
